package com.allen.service;

import com.allen.bean.Result;
import com.allen.bean.User;
import com.allen.mapper.UserMapper;
import com.allen.util.Jwtutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 注册
     * @param user 参数封装
     * @return Result
     */

    public Result regist(User user){
        Result result = new Result();       //实例化对象
        result.setSuccess(false);           //给变量赋值
        result.setDetail(null);
        User exitUser = userMapper.findUserByName(user.getUsername());
        if(exitUser!=null){
            //用户已存在
            result.setMsg("您已注册，请登录!");
        }else{
            userMapper.regist(user);
            System.out.println(user.getId());
            result.setMsg("注册成功,请登录!");
            result.setSuccess(true);
            result.setDetail(user);
        }

        return result;
    }

    /**
     * 登录
     * @param user 用户名和密码
     * @return Result
     */

    public Result login(User user){
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        Long userId= userMapper.login(user);
        User exitUser = userMapper.findUserByName(user.getUsername());
        if(exitUser!=null){
            if(userId==null){
                result.setMsg("用户名或密码错误！");
            }else{
                user.setToken(Jwtutil.createtoken());
                result.setMsg("登陆成功！");
                result.setSuccess(true);
                result.setDetail(user);
            }
        }else{
            result.setMsg("您还未注册，请先注册！");
        }


        return result;
    }
}
